<!-- 用户管理 -->
<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <el-form label-width="80px" :inline="true" size="normal">
      <el-form-item>
        <el-input
          v-model.trim="paramsState.username"
          placeholder="用户名"
          size="normal"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item style="margin: 0px 20px">
        <el-button type="primary" icon="el-icon-search" @click="search"
          >查询</el-button
        >
        <el-button @click="clearSearchUser">清空</el-button>
      </el-form-item>
    </el-form>
    <el-form
      label-width="80px"
      :inline="true"
      size="normal"
      style="margin: 20px 0px"
    >
      <el-form-item>
        <el-button type="primary" @click="add">添加</el-button>
        <el-button
          type="danger"
          :disabled="tableState.selectedIds.length === 0"
          @click="delUserAll"
          >批量删除</el-button
        >
      </el-form-item>
    </el-form>
    <el-table
      ref="multipleTable"
      :data="userList"
      tooltip-effect="dark"
      style="width: 100%"
      border
      @selection-change="handleSelectionChange"
    >
      >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column type="index" label="序号" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名"> </el-table-column>
      <el-table-column prop="nickName" label="用户昵称"> </el-table-column>
      <el-table-column prop="roleName" label="角色列表"></el-table-column>
      <el-table-column prop="gmtCreate" label="创建时间"></el-table-column>
      <el-table-column prop="gmtModified" label="更新时间"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button
            type="info"
            size="small"
            icon="el-icon-user-solid"
            title="分配用户"
            @click="showAssignRole(row)"
          ></el-button>
          <el-button
            type="primary"
            size="small"
            icon="el-icon-edit-outline"
            title="修改用户"
            @click="updataUser(row)"
          ></el-button>
          <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
            title="删除用户"
            @click="delUser(row.id)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :style="{ marginTop: '20px' }"
      :current-page="paramsState.page"
      :page-sizes="[5, 10, 15]"
      :page-size="paramsState.limit"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
    >
    </el-pagination>
    <el-dialog
      :title="userState.user.id ? '修改用户' : '添加用户'"
      :visible.sync="userState.dialogUserVisible"
      width="60%"
    >
      <el-form
        label-width="80px"
        :inline="false"
        :model="userState.user"
        :rules="rules"
      >
        <el-form-item
          label="用户名"
          v-model="userState.user.username"
          prop="username"
        >
          <el-input v-model="userState.user.username"></el-input>
        </el-form-item>

        <el-form-item
          label="用户昵称"
          v-model="userState.user.nickName"
          prop="nickName"
        >
          <el-input v-model="userState.user.nickName"></el-input>
        </el-form-item>
        <el-form-item
          label="用户密码"
          v-model="userState.user.password"
          prop="password"
        >
          <el-input v-model="userState.user.password"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="userState.dialogUserVisible = false"
            >取消</el-button
          >
          <el-button type="primary" @click="addOrUpdataUser">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog
      title="设置角色"
      :visible.sync="roleState.dialogRoleVisible"
      :before-close="resetRoleData"
    >
      <el-form label-width="80px">
        <el-form-item label="用户名">
          <el-input disabled :value="userState.user.username"></el-input>
        </el-form-item>

        <el-form-item label="角色列表">
          <el-checkbox
            :indeterminate="roleState.isIndeterminate"
            v-model="roleState.checkAll"
            @change="handleCheckAllChange"
            >全选</el-checkbox
          >
          <div style="margin: 15px 0"></div>
          <el-checkbox-group
            v-model="roleState.userRoleIds"
            @change="handleCheckedChange"
          >
            <el-checkbox
              v-for="role in roleState.allRoles"
              :key="role.id"
              :label="role.id"
              >{{ role.roleName }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
      </el-form>

      <template #footer >
        <el-button type="primary" @click="assignRole">保存</el-button>
        <el-button @click="resetRoleData">取消</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  reqGetUserList,
  reqAddOrUpdataUser,
  reqDelUser,
  reqDelUserAll,
  reqGetUserToAssign,
  reqDoAssignRoles,
} from "@/api/acl/user.js";
export default {
  name: "user",
  data() {
    return {
      paramsState: {
        username: "",
        searchUsername: "",
        page: 1, // 当前页码
        limit: 5, // 每页数量
      },
      userState: {
        dialogUserVisible: false,
        userLoading: false,
        user: {
          id: "",
          username: "",
          nickName: "",
          password: "",
        },
      },
      total: 0,
      userList: [],
      multipleSelection: [],
      tableState: {
        total: 0,
        users: [],
        selectedIds: [],
      },
      rules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          { min: 4, message: "用户名不能小于4位" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 6, message: "密码不能小于6位" },
        ],
      },
      roleState: {
        dialogRoleVisible: false,
        checkAll: false,
        isIndeterminate: false,
        userRoleIds: [],
        allRoles: [],
      },
    };
  },
  methods: {
    // 获取管理用户列表
    async getUserList() {
      const userList = await reqGetUserList(
        this.paramsState.page,
        this.paramsState.limit,
        {
          username: this.paramsState.searchUsername,
        }
      );
      // console.log(userList.data);
      this.userList = userList.data.items;
      this.total = userList.data.total;
    },
    handleSizeChange(limit) {
      this.paramsState.limit = limit;
      this.getUserList();
    },
    handleCurrentChange(page) {
      this.paramsState.page = page;
      this.getUserList();
    },
    // 点击新增用户的回调
    add() {
      this.userState.dialogUserVisible = true;
      this.userState.user.username = "";
      this.userState.user.nickName = "";
      this.userState.user.password = "";
    },
    // 添加/修改用户
    async addOrUpdataUser() {
      try {
        await reqAddOrUpdataUser(this.userState.user);
        this.userState.dialogUserVisible = false;
        this.$message.success("成功");
        this.getUserList();
      } catch (e) {
        this.$message.error("失败" + e.message);
      }
    },
    // 搜索用户
    search() {
      console.log("111");
      this.paramsState.searchUsername = this.paramsState.username;
      this.getUserList(1);
    },
    // 清空搜索
    clearSearchUser() {
      this.paramsState.username = "";
      this.paramsState.searchUsername = "";
      this.getUserList();
    },
    // 删除用户
    async delUser(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await reqDelUser(id);
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.getUserList();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 修改用户
    updataUser(user) {
      this.userState.user = { ...user };
      this.userState.dialogUserVisible = true;
    },
    // 删除选中的用户
    async delUserAll() {
      try {
        await reqDelUserAll(this.tableState.selectedIds);
        this.$message.success("删除成功");
      } catch (e) {
        this.$message.error("删除失败" + e.message);
      }

      this.getUserList();
    },
    // 列表选中状态的回调  收集选中的id赋值给selectedIds
    handleSelectionChange(selection) {
      this.tableState.selectedIds = selection.map((item) => item.id);
      // console.log(this.tableState.selectedIds);
    },
    // 获取角色数据
    async getUserToAssign() {
      const UserToAssign = await reqGetUserToAssign(this.userState.user.id);
      // console.log(UserToAssign);
      this.roleState.allRoles = UserToAssign.data.allRolesList;
      this.roleState.userRoleIds = UserToAssign.data.assignRoles.map((item) => {
        return item.id;
      });
      // console.log(this.roleState.userRoleIds)
    },
    // 重置用户的数据
    resetRoleData() {
      Object.assign(this.roleState, {
        dialogRoleVisible: false,
        allRoles: [],
        userRoleIds: [],
        isIndeterminate: false,
        checkAll: false,
      });
    },
    handleCheckAllChange(value) {
      this.roleState.userRoleIds = value
        ? this.roleState.allRoles.map((item) => item.id)
        : [];
      // 如果当前不是全选也不全不选时, 指定为false
      this.roleState.isIndeterminate = false;
    },
    handleCheckedChange() {
      const { userRoleIds, allRoles } = this.roleState;
      this.roleState.checkAll =
        userRoleIds.length === allRoles.length && allRoles.length > 0;
      this.roleState.isIndeterminate =
        userRoleIds.length > 0 && userRoleIds.length < allRoles.length;
    },
    // 点击分配用户的回调
    showAssignRole(user) {
      this.userState.user = user;
      this.roleState.dialogRoleVisible = true;
      this.getUserToAssign();
    },
    // 分配角色点击保存的回调
    async assignRole() {
      try {
        const userId = this.userState.user.id;
      // console.log(userId);
      // console.log(this.roleState.userRoleIds);
      const roleId = this.roleState.userRoleIds;
      await reqDoAssignRoles(userId,roleId)
      this.roleState.dialogRoleVisible = false;
      this.getUserList()
      this.$message.success("分配角色成功")
      } catch (e) {
      this.$message.error("分配角色失败"+e.message)
      }
      
    },
  },
  mounted() {
    this.getUserList();
  },
};
</script>

<style scoped></style>
